<?php
if (!function_exists('baidu_site')) {
    /**
     * 百度推广推送
     *
     * @param int $id
     * @return bool
     */
    function baidu_site($id)
    {
        $urls=array();
        $urls[]=url('index/index/article', ['id'=>$id], '', true);
        $api=config('web.baidu_site_url');
        $ch=curl_init();
        $options=array(
            CURLOPT_URL=>$api,
            CURLOPT_POST=>true,
            CURLOPT_RETURNTRANSFER=>true,
            CURLOPT_POSTFIELDS=>implode("\n", $urls),
            CURLOPT_HTTPHEADER=>array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result=curl_exec($ch);
        $msg=json_decode($result, true);
        if ($msg['code']==500) {
            curl_exec($ch);
        }
        curl_close($ch);
    }
}
if (!function_exists('subString')) {
    /**
     * 字符串截取，支持中文和其他编码
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $suffix 截断显示字符
     * @param string $charset 编码格式
     * @return string
     */
    function subString($str, $start, $length, $suffix = true, $charset = 'utf-8')
    {
        if (function_exists('mb_substr')) {
            $slice = mb_substr($str, $start, $length, $charset);
        } elseif (function_exists('iconv_substr')) {
            $slice = iconv_substr($str, $start, $length, $charset);
        } else {
            $re['utf-8']   = '/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/';
            $re['gb2312'] = '/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/';
            $re['gbk']  = '/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/';
            $re['big5']   = '/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/';
            preg_match_all($re[$charset], $str, $match);
            $slice = join('', array_slice($match[0], $start, $length));
        }
            return $suffix ? $slice.'...' : $slice;
    }
}
if (!function_exists('delDirAndFile')) {
    /**
     * 删除文件及文件夹
     *
     * @param string $path   路径
     * @param boolean  $delDir 是否删除目录
     * @return bool
     */
    function delDirAndFile($path, $delDir = false)
    {
        if (is_array($path)) {
            foreach ($path as $subPath) {
                delDirAndFile($subPath, $delDir);
            }
        }
        if (is_dir($path)) {
            $handle = opendir($path);
            if ($handle) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != "." && $item != "..") {
                        is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
                    }
                }
                closedir($handle);
                if ($delDir) {
                    return rmdir($path);
                }
            }
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return false;
            }
        }
            clearstatcache();
    }
}
if (!function_exists('getImgPath')) {
    /**
     * 截取字符串中图片的路径
     * @param  string $str  含有图片链接的字符串
     * @param  string $preg 正则规则
     * @return array        匹配的图片数组
     */
    function getImgPath($str, $preg)
    {
        preg_match_all($preg, $str, $data);
        return current($data);
    }
}
if (!function_exists('createUuid')) {
    /**
     * 生成唯一识别码
     *
     * @param string $namespace 前缀
     * @return void
     */
    function createUuid($prefix = "")
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str, 0, 8) . '-';
        $uuid .= substr($str, 8, 4) . '-';
        $uuid .= substr($str, 12, 4) . '-';
        $uuid .= substr($str, 16, 4) . '-';
        $uuid .= substr($str, 20, 12);
        return $prefix . $uuid;
    }
}
if (!function_exists('getAddressFromIp')) {
    /**
     * 获取IP地址位置
     * @param  string $ip   ip地址
     * @return string       生成ip所在地址
     */
    function getAddressFromIp($ip)
    {
        if ($ip == '127.0.0.1') {
            return '本地/内网访问';
        }
        $urlSina = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=' . $ip;
        $json = file_get_contents($urlSina);
        $jsonDecode = json_decode($json);
        $data['country'] = $jsonDecode->country;
        $data['province'] = $jsonDecode->province;
        $data['city'] = $jsonDecode->city;
        $data['isp'] = $jsonDecode->isp;
        $data['district'] = $jsonDecode->district;
        return $data['province'] . '/' . $data['city'];
    }
}
if (!function_exists('transTime')) {
    /**
     * 传入时间戳,计算距离现在的时间
     * @param  number $time 时间戳
     * @return string     返回多少以前
     */
    function transTime($time)
    {
        $time = (int)substr($time, 0, 10);
        $int = time() - $time;
        $str = '';
        if ($int <= 2) {
            $str = sprintf('刚刚', $int);
        } elseif ($int < 60) {
            $str = sprintf('%d秒前', $int);
        } elseif ($int < 3600) {
            $str = sprintf('%d分钟前', floor($int / 60));
        } elseif ($int < 86400) {
            $str = sprintf('%d小时前', floor($int / 3600));
        } elseif ($int < 1728000) {
            $str = sprintf('%d天前', floor($int / 86400));
        } else {
            $str = date('Y-m-d H:i:s', $time);
        }
        return $str;
    }
}
if (!function_exists('passwdSet')) {
    /**
     * 密码加密
     * @param string $pass  密码明文
     * @return string       密码密文
     */
    function passwdSet($plain)
    {
        $passwd = new \Password\Password;
        $bcryptPass = $passwd->setPassword($plain);
        return $bcryptPass;
    }
}
if (!function_exists('passwdVerify')) {
    /**
     * 密码验证
     * @param string $plain  密码明文
     * @param string $pass   密码密文
     * @return bool
     */
    function passwdVerify($plain, $hash)
    {
        $passwd = new \Password\Password;
        $verifyPass = $passwd->verifyPassword($plain, $hash);
        return $verifyPass;
    }
}
if (!function_exists('getRandPassword')) {
    /**
     * 生成随机密码
     * @param integer $length
     * @return string 密文
     */
    function getRandPassword($length = 8)
    {
        $password = '';
        $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $char_len = strlen($chars);
        for ($i=0; $i<$length; $i++) {
            $loop = mt_rand(0, ($char_len-1));
            $password .= $chars[$loop];
        }
        return $password;
    }
}
if (!function_exists('md2html')) {
    /**
 * Markdown转换Html
 *
 * @param string $string 要转换的markdown
 * @return string
 */
    function md2html($string)
    {
        $parser = new HyperDown\Parser;
        $html = $parser->makeHtml(htmlspecialchars_decode($string));
        return removeXSS($html);
    }
}
if (!function_exists('removeXSS')) {
    /**
     * XSS过滤
     *
     * @param string $dirty_html 要过滤的内容
     * @return string            过滤后的内容
     */
    function removeXSS($dirty_html)
    {
        $config = HTMLPurifier_Config::createDefault();
        $purifier = new HTMLPurifier($config);
        $clean_html = $purifier->purify($dirty_html);
        return $clean_html;
    }
}
if (!function_exists('sendMail')) {
/**
 * PHPMailer发送邮件(可群发)
 * @param string|array $sendTo    收件人（可数组）
 * @param string $subject  主题
 * @param string $content  内容
 * @return arrray
 */
    function sendMail($sendTo, $subject, $content)
    {
        date_default_timezone_set('Asia/Shanghai');
        $mail = new PHPMailer;
        $mail->CharSet = 'utf-8';
        $mail->isSMTP();
        $mail->Host = config('web.mail_Host');
        $mail->SMTPAuth = true;
        $mail->Username = config('web.mail_Username');
        $mail->Password = config('web.mail_Password');
        $mail->SMTPSecure = config('web.mail_SMTPSecure');
        $mail->Port = config('web.Port');
        $mail->setFrom(config('web.mail_Username'), config('web.mail_FromName'));
        if (is_array($sendTo)) {
            foreach ($sendTo as $addressv) {
                $mail->AddAddress($addressv);
            }
        } else {
            $mail->AddAddress($sendTo);
        }
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $content;
        if (!$mail->send()) {
            return ['errno'=>1,'msg'=>$mail->ErrorInfo];
        } else {
            return ['errno'=>0,'msg'=>'发送成功'];
        }
    }
}
